package info.davidesposito.bamboomonitor.web;

import info.davidesposito.bamboomonitor.display.BambooDisplay;
import info.davidesposito.bamboomonitor.display.DisplayModule.DisplayStatus;
import info.davidesposito.bamboomonitor.loops.BambooLoop;
import info.davidesposito.bamboomonitor.loops.BambooLoopModule;
import info.davidesposito.bamboomonitor.loops.BambooLoopModule.BuildStatus;
import info.davidesposito.bamboomonitor.loops.BambooLoopModule.LoopStatus;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class StandardBambooMonitor implements BambooMonitor {
	
	private boolean keepGoing;
	private final BambooDisplay display;
	
	public StandardBambooMonitor(BambooDisplay display) {
		keepGoing = true;
		this.display = display;
	}
	
	@Override
	public synchronized boolean monitorIsAlive() {
		return keepGoing;
	}
	
	@Override
	public synchronized void kill() {
		keepGoing = false;
	}

	@Override
	public void run() {
		while(keepGoing) {
			parseDocuement(getDocument(BambooMonitorModule.SECONDARY_WEB_PAGE_QUERY_ADDRESS));
			System.out.println(BambooLoopModule.CORE_COMMUNITY_LOOPS);
			System.out.println("Display Status: " + display.getDisplayStatus());
			if (display.getDisplayStatus() == DisplayStatus.CONNECTED) {
				display.update();
			}
			try {
				Thread.sleep(BambooMonitorModule.DEFAULT_REFRESH_DELAY);
			} catch (InterruptedException e) {
				// do nothing
			}
		}
	}

	private Document getDocument(String url) {
		Document doc = null;
		try {
			// TODO: Implement logs
//			System.out.println("Connecting to url: " + url);
			Connection con = Jsoup.connect(url);
			doc = con.get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}
	
	private void parseDocuement(Document doc) {
		if (doc == null) {
			throw new IllegalArgumentException();
		}
		Map<String, BambooLoop> loopMap = BambooLoopModule.CORE_COMMUNITY_LOOPS_MAP;
		for (Entry<String, BambooLoop> e : loopMap.entrySet()) {
			String id = BambooMonitorModule.LOOP_ID_PREFIX + e.getKey();
			Element loopEle = doc.getElementById(id);
			LoopStatus loopStatus;
			{
				Set<String> successClassNames = loopEle.parent().classNames();
				loopStatus = successClassNames.contains("Successful") ? 
						LoopStatus.PASSING : LoopStatus.FAILING;
			}
			BuildStatus buildStatus;
			{
				loopEle = loopEle.parent().parent();
				Element buildStatusEle = loopEle.getElementsByClass("statusIcon").first()
						.getElementsByTag("img").first();
				boolean building = buildStatusEle.attr("src").contains("building");
				buildStatus = building ? BuildStatus.BUILDING : BuildStatus.WAITING;
			}
			BambooLoop loop = e.getValue();
			synchronized (loop) {
				loop.setLoopStatus(loopStatus);
				loop.setBuildStatus(buildStatus);
			}
		}
	}
}
